package com.yaoweigroup.community.ui.my;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Rsa;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.MyDsicountOrderAdapter;
import com.yaoweigroup.community.adapter.MyOrderAdapter;
import com.yaoweigroup.community.adapter.MyWtAdapter;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.dialog.DialogCallBack;
import com.yaoweigroup.community.enity.DiscountOrder;
import com.yaoweigroup.community.enity.OrderInfo;
import com.yaoweigroup.community.enity.SportOrder;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.interfaze.Callback;
import com.yaoweigroup.community.ui.bm.OrderSubmitActivity;
import com.yaoweigroup.community.util.ApkDownloadUtil;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 我的优惠信息
 * 
 * @author xi
 * 
 */
public class MyWTActivity extends Activity implements OnClickListener, Callback {

	private RelativeLayout left_rl;
	private PullToRefreshListView listView;
	private MyWtAdapter adapter;
	private List<SportOrder> list;

	public final int ORDER_SUCCESS = 0x2210;
	public final int ORDER_FAIL = ORDER_SUCCESS + 1;
	public final int CANCEL_SUCCESS = ORDER_SUCCESS + 2;
	public final int CANCEL_FAIL = ORDER_SUCCESS + 3;
	public final int NEED_LOGIN = ORDER_SUCCESS + 4;
	public final int RQF_PAY = ORDER_SUCCESS + 5;
	private ProgressBar progress;

	private SharePreferenceUtil util;
	private ObjectMapper mapper;

	private ImageView error_iv;

	private Dialog dialog;
	private TextView center_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_order);

		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("我的文体预订");
		dialog = DialogUtil.createWaitDialog(this, "正在取消中...");
		mapper = new ObjectMapper();
		util = new SharePreferenceUtil(this, Constant.prf);
		progress = (ProgressBar) findViewById(R.id.progress);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		list = new ArrayList<SportOrder>();
		listView = (PullToRefreshListView) findViewById(R.id.listView);
		adapter = new MyWtAdapter(this, list);
		adapter.setCallback(this);
		listView.setAdapter(adapter);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		obtainData();
	}

	private void obtainData() {
		user = (UserInfo) util.loadObject("user");
		if (user != null) {
			listOrder(user.getUid());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case ORDER_FAIL:
				error_iv.setVisibility(View.VISIBLE);
				progress.setVisibility(View.GONE);
				break;
			case ORDER_SUCCESS:
				if (orders != null && orders.size() > 0) {
					list.addAll(orders);
				}
				if (list.size() == 0) {
					error_iv.setVisibility(View.VISIBLE);
				}
				Collections.reverse(list);
				adapter.setDataChange(list);
				progress.setVisibility(View.GONE);
				break;
			case CANCEL_FAIL:
				Toast.makeText(MyWTActivity.this, "距离预定的场馆时间3天内不能取消!", 500).show();
				break;
			case CANCEL_SUCCESS:
				list.clear();
				adapter.setDataChange(list);
				obtainData();
				break;
			case LoginUtil.LOGIN_FAIL:
				progress.setVisibility(View.GONE);
				break;
			case LoginUtil.LOGIN_SUCCESS:
				if (isCancel) {
					cancelOrder(orderId);
				} else {
					obtainData();
				}
				break;
			case NEED_LOGIN:
				LoginUtil.isLoginSuccess(MyWTActivity.this, handler, mapper);
				break;
			case RQF_PAY:

				break;
			}
		};
	};

	/**
	 * 获取订单列表
	 */
	private UserInfo user;
	private int pageSize = 10;
	private int pageNo = 1;
	private List<SportOrder> orders;

	private void listOrder(String uid) {
		orders = new ArrayList<SportOrder>();
		user = (UserInfo) util.loadObject("user");
		progress.setVisibility(View.VISIBLE);
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		// jsonUtil.add("pageNo", pageNo + "");
		// jsonUtil.add("pageSize", pageSize + "");
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getMyBookings, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						try {
							JSONObject obj = new JSONObject(responseInfo.result);
							String data = obj.getString("Data");
							int state = obj.getInt("state");
							if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else if (state == 200) {
								orders = mapper.readValue(data,
										new TypeReference<List<SportOrder>>() {
										});
								handler.sendEmptyMessage(ORDER_SUCCESS);
							} else {
								handler.sendEmptyMessage(ORDER_FAIL);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(ORDER_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(ORDER_FAIL);
					}

				});
	}

	/**
	 * 取消订单
	 */
	private boolean isCancel = false;
	private String orderId = null;

	private void cancelOrder(String orderNum) {
		dialog.show();
		isCancel = true;
		UserInfo user = (UserInfo) util.loadObject("user");
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("seat_order_guid", orderNum);
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.cancelSeatOrderTransaction,
				params, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else if (state == 200) {
								handler.sendEmptyMessage(CANCEL_SUCCESS);
							} else {
								handler.sendEmptyMessage(CANCEL_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(CANCEL_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(CANCEL_FAIL);

					}

				});
	}

	@Override
	public void callback(String id, int tagId, double price) {
		orderId = id;
		DialogUtil.versionDialog(MyWTActivity.this, "是否取消确定",
				new DialogCallBack() {

					@Override
					public void viewClick() {
					}

					@Override
					public void ok() {
						cancelOrder(orderId);
					}

					@Override
					public void init(Object obj) {

					}

					@Override
					public void cancel() {

					}
				}, "确定", "取消");

	}

}
